package com.wechat.bot.quartz;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.wechat.bot.common.log.Log;
import com.wechat.bot.entity.WarningInfo;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.stream.Collectors;

/**
 * @author 尹波宁
 * @create 2023-10-04 16:23
 */
@Component
@EnableScheduling
public class quartz {

    @Value("${spring.rabbitmq.exchangename}")
    private  String EXCHANGE_NAME;
    @Value("${spring.rabbitmq.routingname}")
    private String ROUTING_NAME;


    @Value("${threshold}")
    private Double threshold;


    @Autowired
    private RabbitTemplate rabbitTemplate;


    @Scheduled(cron = "${quartz}")
    public void indexClean() throws IOException {

        CloseableHttpClient client = HttpClients.createDefault();

        HttpPost httpPost = new HttpPost("https://api.ddpurse.com/phoenix/public/nft_intl_get_work_group_list");

        // 设置请求头
        httpPost.setHeader("Host", "api.ddpurse.com");
        httpPost.setHeader("Connection", "keep-alive");
        httpPost.setHeader("sec-ch-ua", "\"Google Chrome\";v=\"117\", \"Not;A=Brand\";v=\"8\", \"Chromium\";v=\"117\"");
        httpPost.setHeader("app-version", "2.2.0");
        httpPost.setHeader("accept-language", "zh-CN");
        httpPost.setHeader("sec-ch-ua-mobile", "?0");
        httpPost.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/117.0.0.0 Safari/537.36");
        httpPost.setHeader("content-type", "application/json");
        httpPost.setHeader("client-id", "13f36a97f0250bc2ee128b572b85faa4");
        httpPost.setHeader("sec-ch-ua-platform", "\"Windows\"");
        httpPost.setHeader("Accept", "*/*");
        httpPost.setHeader("Origin", "https://h5.foreverrealm.vip");
        httpPost.setHeader("Sec-Fetch-Site", "cross-site");
        httpPost.setHeader("Sec-Fetch-Mode", "cors");
        httpPost.setHeader("Sec-Fetch-Dest", "empty");
        httpPost.setHeader("Referer", "https://h5.foreverrealm.vip/");

        // 设置请求体
        String json = "{\"page\":1,\"page_size\":30,\"filter\":{\"status\":\"on-shelf\",\"keyword\":\"\",\"type\":\"\",\"category_id\":\"6267b1f3319840000108ca65\",\"without_user_index\":false,\"user_id\":\"\"}}";
        HttpEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
        httpPost.setEntity(entity);

        CloseableHttpResponse response = null;
        try {
            response = client.execute(httpPost);
            HttpEntity responseEntity = response.getEntity();
            String responseBody = EntityUtils.toString(responseEntity);
            JSONObject responseJson = JSON.parseObject(responseBody);
            JSONObject dataObject = responseJson.getJSONObject("data");

            if (dataObject != null) {
                JSONArray itemsArray = dataObject.getJSONArray("items");
                if(itemsArray != null && !itemsArray.isEmpty()){
                    CopyOnWriteArrayList<WarningInfo> warnList;

                    warnList=itemsArray.parallelStream()
                            .map(item -> {
                                JSONObject itemJson = JSON.parseObject(item.toString());
                                Object nft_info = itemJson.get("nft_info");
                                return JSON.parseObject(nft_info.toString(), WarningInfo.class);
                            })
                            .filter(info -> {
                                double ratio = Double.parseDouble(info.getFiat_price_range().split(" ")[0]);
                                double recentPrice = Double.parseDouble(info.getRecent_transaction_fiat_price_str().split(" ")[0]);
                                return ratio / recentPrice < threshold;
                            }).collect(Collectors.toCollection(CopyOnWriteArrayList::new));

                    if ( warnList.size() > 0){
                        Log.info("开始发送预警消息");
                        sendRabbitMQMessage(warnList);
                    }

                }
            }

        } finally {
            if (response != null) {
                response.close();
            }
            client.close();
        }
    }

    private void sendRabbitMQMessage(CopyOnWriteArrayList<WarningInfo> warnList) {
        try {
            String rabbitString = JSON.toJSONString(warnList);
            //发送消息
            Log.info("开始推送消息,共"+warnList.size()+"条");
            rabbitTemplate.convertAndSend(EXCHANGE_NAME,ROUTING_NAME,rabbitString);
        } catch (Exception e) {
            Log.info("发送消息异常" + e.getMessage());
        }
    }

}
